package com.aggron.service.impl;

import com.aggron.bean.PageQuery;
import com.aggron.bean.PageResult;
import com.aggron.dao.SysRoleMapper;
import com.aggron.entity.SysRole;
import com.aggron.exception.ParamException;
import com.aggron.params.RoleParams;
import com.aggron.service.ISysRoleService;
import com.aggron.util.BeanValidator;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuhuan
 * @since 2018-06-02
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public void save(RoleParams roleParams) {
        BeanValidator.check(roleParams);
        if(checkExist(roleParams.getName(),roleParams.getId())){
            throw new ParamException("角色名称已经存在");
        }
        SysRole sysRole=SysRole.builder().name(roleParams.getName()).remark(roleParams.getRemark()).type(roleParams.getType()).status(roleParams.getStatus()).build();
        sysRole.setOperator("admin");//TODO
        sysRole.setOperateIp("127.0.0.1");//TODO
        sysRole.setOperateTime(new Date());

        sysRoleMapper.insert(sysRole);
    }

    private boolean checkExist(String name, Integer id) {
        return false;//TODO
    }

    @Override
    public void update(RoleParams roleParams) {
        BeanValidator.check(roleParams);
        if(checkExist(roleParams.getName(),roleParams.getId())){
            throw new ParamException("角色名称已经存在");
        }
        SysRole before=sysRoleMapper.selectById(roleParams.getId());
        Preconditions.checkNotNull(before,"待更新的角色点不存在");

        SysRole after=SysRole.builder().id(roleParams.getId()).name(roleParams.getName()).remark(roleParams.getRemark()).type(roleParams.getType()).status(roleParams.getStatus()).build();
        after.setOperator("admin");//TODO
        after.setOperateIp("127.0.0.1");//TODO
        after.setOperateTime(new Date());
        sysRoleMapper.updateById(after);
    }

    /**
     * 分页查询角色
     * @param pageQuery
     * @param roleParams
     * @return
     */
    @Override
    public PageResult<Map<String, Object>> pageRole(PageQuery pageQuery, RoleParams roleParams) {
        Page page=new Page(pageQuery.getCurrent(),pageQuery.getPageSize());
        List<Map<String,Object>> roleList=sysRoleMapper.listRole(page,roleParams);
        int count =sysRoleMapper.countRole(roleParams);

        PageResult<Map<String,Object>> pageResult=new PageResult(roleList,count,pageQuery);
        return pageResult;
    }
}
